package com.soso.base.google.cron.schedule;

import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.soso.base.util.log.Logger;

public class ScheduleRuleC extends AbstractScheduleRule implements ScheduleRule{
	
	private static final String REGEX="^every (\\b.+\\b) (\\d+:\\d+)$";	
	
	public static void main(String []args){
		ScheduleBean scheduleBean=new ScheduleBean();
		scheduleBean.setScheduleTime("every sunday,monday,tuesday,friday,saturday 09:18");
		ScheduleRule scheduleRule=new ScheduleRuleC();
		scheduleRule.execute(scheduleBean,null);
	}
	
	/**
	 * sunday,monday,tuesday,wednesday,thursday,friday,saturday
	 * every day 10:00
	 */
	@Override
	public boolean execute(ScheduleBean scheduleBean,ScheduleRuleChain chain) {
		Pattern p = Pattern.compile(REGEX, Pattern.DOTALL);
        Matcher m = p.matcher(scheduleBean.getScheduleTime());
        if(!m.find()){
        	return chain.execute(scheduleBean);
        }
        Logger.debug(REGEX);
        String days=m.group(1).toLowerCase();
        String times[]=m.group(2).split(":");
        int hh=Integer.parseInt(times[0]);
        int mm=Integer.parseInt(times[1]);
        if(!days.equals("day")&&days.indexOf(getWeek())==-1){
        	return false;
        }
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        Logger.debug("计划时间："+hh+":"+mm);
        Logger.debug("现在时间："+now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE));
        if(hh!=now.get(Calendar.HOUR_OF_DAY)||mm!=now.get(Calendar.MINUTE)){
        	return false;
        }
        //更新缓存
        Logger.debug("SUCCESS");
        scheduleBean.setLastTime(now.getTime());
        return true;
	}
	

}
